/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var zigzagLevelOrder = function(root) {
    var res = [];

    levelOrderWithDepth(root, res, 0);

    res.forEach((value, index)=>{
       if(index%2)value = value.reverse();
    });

    return res;
};

function levelOrderWithDepth(node, arr, depth) {
    if(!node)return;

    if(!Array.isArray(arr[depth])){
        arr[depth] = [];
    }

    arr[depth].push(node.val);

    depth++;

    levelOrderWithDepth(node.left, arr, depth);
    levelOrderWithDepth(node.right, arr, depth);

}